package com.eastedu.template.thread;

import org.apache.commons.lang3.ThreadUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用来处理任务中断
 *
 * @author ZhenZhong
 */
public class HandlerSemaphore {
    private static final Map<String, Boolean> RUNNING_STATS = new ConcurrentHashMap<>();

    private static final Map<String, Long> THREAD_INFO = new ConcurrentHashMap<>();

    /**
     * Record.
     *
     * @param taskId the task id
     */
    public static void record(String taskId) {
        THREAD_INFO.put(taskId, Thread.currentThread().getId());
        set(taskId, true);
    }

    /**
     * Set.
     *
     * @param taskId    the task id
     * @param interrupt the interrupt
     */
    public static void set(String taskId, boolean interrupt) {
        RUNNING_STATS.put(taskId, interrupt);
    }

    /**
     * Is interrupted boolean.
     *
     * @param taskId the task id
     * @return the boolean
     */
    public static boolean isInterrupted(String taskId) {
        Boolean s = RUNNING_STATS.get(taskId);
        return s == null || !s;
    }

    /**
     * Remove.
     *
     * @param taskId the task id
     */
    public static void remove(String taskId) {
        RUNNING_STATS.remove(taskId);
        THREAD_INFO.remove(taskId);
    }

    /**
     * Terminate.
     *
     * @param taskId the task id
     */
    public static void terminate(String taskId) {
        Long id = THREAD_INFO.get(taskId);
        if (Objects.nonNull(id)) {
            Thread thread = ThreadUtils.findThreadById(id);
            if (Objects.nonNull(thread)) {
                thread.interrupt();
                remove(taskId);
            }
        }
    }
}
